package com.alt.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.Toast;

import com.alt.adapter.ListAdAdapter;
import com.alt.base.ALTTabActivity;
import com.alt.handler.CMCmdHandler;
import com.alt.manager.ALTAppMgr;
import com.alt.manager.ALTPTCMgr;
import com.alt.manager.ALTPTCMgr.SCREEN_UI;
import com.alt.models.AdsInfo;
import com.alt.models.AdsModel;
import com.alt.models.ImageModel;
import com.alt.R;
import com.costum.android.widget.LoadMoreListView;
import com.costum.android.widget.LoadMoreListView.OnLoadMoreListener;

public class ALTHome extends ALTTabActivity {

	private EditText edSearch;
	private LoadMoreListView lvListAd;
	ListAdAdapter dataAdapter = null;
	private ArrayList<AdsModel> ADSMODEL = new ArrayList<AdsModel>();
	private AdsInfo[] adsLst;
	private boolean loadmore = false;	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
//		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		setContentView(R.layout.screen_home);
		onSetScreenMode(SCREEN_UI.HOME);
		
		

		edSearch = (EditText) findViewById(R.id.edSearch);
		lvListAd = (LoadMoreListView) findViewById(R.id.lvListAd);
		
		((LoadMoreListView) lvListAd)
		.setOnLoadMoreListener(new OnLoadMoreListener() {
			public void onLoadMore() {
				// Do the work to load more items at the end of list
				// here
				//new LoadDataTask().execute();						
				loadmore = true;
				
				if(ADSMODEL.size()%15==0 || ALTAppMgr.getInstance().getAllow2Loadmore()){
					Bundle b = new Bundle();
					b.putString("userid", ALTAppMgr.getInstance().getUserLogInfo().UserId);
					b.putString("loadeditemcount", String.valueOf(ADSMODEL.size()));
					ALTAppMgr.getInstance().startServiceCmd(CMCmdHandler.COMMAND_GET_ADS_LIST_BY_USERID,new CMCmdHandler(), b,false);									
				}else{
					((LoadMoreListView) lvListAd).onLoadMoreComplete();	
				}				
			}
		});				
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		//loadAdsData(ALTAppMgr.getInstance().getAdsLstData().toArray(new AdsInfo[ALTAppMgr.getInstance().getAdsLstData().size()]));
		
		// Load Ads list
		Bundle b = new Bundle();
		b.putString("userid", ALTAppMgr.getInstance().getUserLogInfo().UserId);
		b.putString("loadeditemcount", "0");
		ALTAppMgr.getInstance().startServiceCmd(CMCmdHandler.COMMAND_GET_ADS_LIST_BY_USERID, new CMCmdHandler(), b, true);
	}
	
	private void loadAdsData(AdsInfo[] adsLst){		 
		 ADSMODEL = new ArrayList<AdsModel>();
		 
		 for (int i = 0; i < adsLst.length; i++) {
		     AdsModel ap = new AdsModel(adsLst[i].AdsID,adsLst[i].Title, adsLst[i].FaviconIcon,adsLst[i].AprovedDate,adsLst[i].Rating,adsLst[i].Fee);
		     ADSMODEL.add(ap);			
		 }			 
			dataAdapter = new ListAdAdapter(this, R.layout.item_list_menu, ADSMODEL);
			lvListAd.setAdapter(dataAdapter);
			//new LoadIconsTask().execute(ADSMODEL.toArray(new AdsModel[]{}));
	}
	
	@Override
	public void processCommandResult(int commandCode, Object resultData) {
		// TODO Auto-generated method stub
		super.processCommandResult(commandCode, resultData);
		
		Bundle bResult = (Bundle) resultData;

		switch(commandCode){		
		     
		 case CMCmdHandler.COMMAND_GET_ADS_LIST_BY_USERID:{
			 adsLst = (AdsInfo[]) bResult.getSerializable(ALTPTCMgr.REST_OBJECT_RETURN);	
			 
			 if(!loadmore){				 
				 loadAdsData(adsLst);				
		     }else{
		 			 for (int i = 0; i < adsLst.length; i++) {
					     AdsModel ap = new AdsModel(adsLst[i].AdsID,adsLst[i].Title, adsLst[i].FaviconIcon,adsLst[i].AprovedDate,adsLst[i].Rating,adsLst[i].Fee);
					     ADSMODEL.add(ap);			
					 }	
					 
			    	 if( ALTAppMgr.getInstance().getAllow2Loadmore()){
			    		 ALTAppMgr.getInstance().setAllow2Loadmore(false);

			    		 if(ALTAppMgr.getInstance().getAdsLstData().size() < 15 &&  adsLst.length > 0){
			    			 List<AdsInfo> adlst = ALTAppMgr.getInstance().getAdsLstData();
			    			//update current temporary ADS list to full 15 elements
			    			 for (int i = 0; i < 			    					 
			    					( adsLst.length - (15-ALTAppMgr.getInstance().getAdsLstData().size()) > 0 ?
			    							 (15-ALTAppMgr.getInstance().getAdsLstData().size()) : adsLst.length) 
			    					 
			    					 ; i++) {
			    			
			    				 adlst.add(adsLst[i]);
			    			 }							
			    			 ALTAppMgr.getInstance().setAdsLstData(adlst);
							}
			    		 }
		 			 
			     	((LoadMoreListView) lvListAd).onLoadMoreComplete();
			        dataAdapter.updateNewAdsModelList(ADSMODEL);				        
		   }
			 
//			 new LoadIconsTask().execute(ADSMODEL.toArray(new AdsModel[]{}));
		 }
		    break;
		    
			case CMCmdHandler.COMMAND_GET_ADS_IMAGE_LIST: {
				ImageModel imgData = (ImageModel) bResult.getSerializable(ALTPTCMgr.REST_OBJECT_RETURN);
				//ALTAppMgr.getInstance().cleanCacheLocal(this);
	
				if (imgData.AdsID.isEmpty()) {
					Toast.makeText(this, "This Ad has no image", Toast.LENGTH_SHORT).show();
				} else {					
					
					String fee = "0";
					for (AdsModel item : ADSMODEL) {
						if(item.getAdsid().equals(imgData.AdsID)){
							fee = item.getFee();
							break;
						}
					}
					
					Intent i = new Intent(this, ALTViewImage.class);
					i.putExtra("ImageModel", imgData);
					i.putExtra("Fee", fee);				
					
					startActivityForResult(i, 1);					
				}

			}
				break;
				
			case CMCmdHandler.COMMAND_UPDATE_PROFILE_PICTURE:{
				String value = bResult.getString(ALTPTCMgr.REST_OBJECT_RETURN);
				Toast.makeText(this, value, Toast.LENGTH_LONG).show();
			}
				break;
		 
		 default:
			 break;		
		}			
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
	       if(data.getExtras().containsKey("mResult")){	    	   
	    	   Toast.makeText(this, data.getStringExtra("mResult") , Toast.LENGTH_SHORT).show();	    	   
	    	}

	}
	
//	   private class LoadIconsTask extends AsyncTask<AdsModel, Void, Void> {
//		      @Override
//		      protected Void doInBackground(AdsModel... apps) {		         
//		         Map<String, byte[]> icons = new HashMap<String, byte[]>();		        
//		         
//		         for (AdsModel app : apps) {
//		            icons.put(app.getAdsid(), app.getImageId());
//		         }
//		         dataAdapter.setIcons(icons);		         
//		         return null;
//		      }
//		      
//		      @Override
//		      protected void onPostExecute(Void result) {
//		    	  dataAdapter.notifyDataSetChanged();		    	  
//		    	  //Toast.makeText(getApplicationContext(), String.valueOf(lvListAd.getLastVisiblePosition()), Toast.LENGTH_LONG).show();
//		      }
//		  }
	   
	   @Override
	public void onScreenChanged(SCREEN_UI curScreen) {
		// TODO Auto-generated method stub
		super.onScreenChanged(curScreen);
	}

}
